from datetime import datetime
import requests
import json

class BaiduTranslate:

    def __init__(self):
        pass

    # 翻译"from_lanuage":"zh","to_lanuage":"en"
    def translate(self, text, from_lanuage, to_lanuage):
        timestamp = datetime.now().timestamp()
        tt = int(timestamp * 1000)
        jsonStr = {"query":text,"from":from_lanuage,"to":to_lanuage,"reference":"","corpusIds":[],"needPhonetic":False,"domain":"common","milliTimestamp":tt}
        response = None
        try:
            response = requests.post("https://fanyi.baidu.com/ait/text/translate", json=jsonStr, verify=False, timeout=(20, 120), stream=True)
            for line in response.iter_lines():
                str_data = line.decode("utf-8")
                if str_data=="event: message" or str_data is None or str_data=="" :
                    continue
                str_data = str_data.replace("data: ", "")
                response_json = json.loads(str_data)
                # 获取事件
                if response_json["data"]["event"]!="Translating":
                    continue
                # 获取翻译数据
                list = response_json["data"]["list"]
                if len(list)>0 and "dst" in list[0]:
                    return list[0]["dst"]
        except Exception as e:
            self.log.exception(f"百度翻译异常:")
            return ""

if __name__ == "__main__":
    #from func.translate.baidu_translate import BaiduTranslate
    baiduTranslate = BaiduTranslate()
    text = baiduTranslate.translate("你好啊","zh","en")
    print(text)